package com.pj.ca.service.impl;

import com.pj.ca.common.LocalCaConstant;
import com.pj.ca.config.AppConfig;
import com.pj.ca.config.CaConfig;
import com.pj.ca.modal.CertReq;
import com.pj.ca.modal.CertResult;
import com.pj.ca.modal.KeyPairResult;
import com.pj.ca.service.CertManageService;
import com.pj.ca.util.CertUtil;
import com.pj.ca.util.KeyPairUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;

/**
 * 描述：
 *
 * @author pengjun
 * @date 2021/11/3 16:52
 */
@Service
public class CertManageServiceImpl implements CertManageService {

    @Autowired
    AppConfig appConfig;

    @Override
    public CertResult certToUser(CertReq req, Integer keySize) throws Exception {
        CaConfig caConfig = appConfig.getByKeyType(req.getCatype());
        CertResult certResult = new CertResult();
        String signAlg = req.getSignAlg() == null ? caConfig.getSignAlg() : req.getSignAlg();
        KeyPairResult keyPairResult = KeyPairUtil.gen(LocalCaConstant.KeyType.forValue(req.getCatype()), keySize);
        PublicKey pub = keyPairResult.getPub();
        PrivateKey pri = keyPairResult.getPri();
        X509Certificate userCert = CertUtil.makeUserCert(pub, caConfig.getPub(), caConfig.getPri(),
                caConfig.getIssuerDN(), req.getUserDN(), req.getNotBefore(), req.getNotAfter(),
                new BigInteger(req.getSerialNumber()), signAlg);
        certResult.setPri(pri);
        certResult.setPub(pub);
        certResult.setCert(userCert);
        return certResult;

    }

    @Override
    public KeyPairResult createKeyPair(LocalCaConstant.KeyType type, Integer keySize) throws Exception {
        KeyPairResult keyPairResult = KeyPairUtil.gen(type, keySize);
        return keyPairResult;
    }
}
